<?php

namespace app\admin\controller\shop\user;

use app\admin\controller\shop\Base;
use app\shop\enums\user\UserMoneyChangeType;
use app\shop\service\LogService;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;
use Throwable;

/**
 * 用户管理
 */
class User extends Base
{
    /**
     * User模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\user\User
     */
    protected object $model;

    protected array|string $preExcludeFields = [];

    protected string|array $quickSearchField = ['nickname'];

    protected array $withJoinTable = ['level', 'shopUser', 'partner'];

    protected bool $modelSceneValidate = true;

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\user\User;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * @return void
     * @throws Throwable
     * @throws DbException
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $res->visible(['level' => ['name'], 'partner' => ['name']])->each(function ($item) {
            $item->mobile = substr_replace($item->mobile, '****', 3, -4);
            if($item->grade_id){
                $item->grade_name = Db::name('shop_user_grade')->where('id',$item->grade_id)->value('name');
            }
            if($item->pid){
                $item->pid = $this->model->where('id',$item->pid)->value('nickname');
            }
        });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 调整余额
     * @return void
     */
    public function editBalance(): void
    {
        $params = $this->request->post();

        try {
            (new \app\admin\validate\shop\user\User())->scene('edit_balance')->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        try {
            LogService::userMoneyLog($params['user_id'], $params['money'], $params['memo'], UserMoneyChangeType::SYSTEM_OPERATE);
        } catch (Throwable $e) {
            $this->error('余额调整失败,请刷新重试', ['err' => $e->getMessage()]);
        }

        $this->success('调整成功');
    }
}